/*************************************************************************
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ************************************************************************/


/**
 * @file
 * PortManager.h
 *
 * @author
 * Pavel Hasenohrl (<a href="mailto:hasenpav@fel.cvut.cz">hasenpav@fel.cvut.cz</a>)
 *
 * @brief
 * This header contains class which manages creations of sessions.
 */


#ifndef _PORT_MANAGER_H
#define _PORT_MANAGER_H

#include "Config.h"

extern "C" {
#include <pthread.h>
}

/**
 * @brief
 * Class which is used by sessions.
 */
class CPortManager {
  const CConfig &m_conf;
  pthread_mutex_t m_mutex;

  struct PortRange {
    long *plStates;
    unsigned short usLow, usHigh, usNext, usSize, usUsed;
  };
  PortRange m_SipPorts, m_RtpPorts;
public:
  CPortManager(const CConfig &conf);
  ~CPortManager();

  /**
   * @brief Initialize object according to config parameters.
   * @return true when completes successfully
   */
  bool Init();
    
  /**
   * @brief Retrieves config parameter.
   * @param[in] enum identifies config parameter to retrieve, mustn't be CE_MAXENTRY
   * @return const value of config parameter
   */
  const std::string &GetValue(ConfigEntry ce) const { return m_conf.GetConfigEntry(ce); }

  /**
   * @brief Retreives free sip or rtp port number, marks the port number as not free.
   * @param[in] bRtp if true, in usPort will be rtp port number otherwise sip port number   
   * @param[out] usPort potentially free port number
   * @return true if there is free port number
   */
  bool GetPort(bool bRtp, unsigned short &usPort);
  /**
   * @brief Mark previously used sip port number as free
   * @param[in] bRtp release rtp port number otherwise sip port number   
   * @param[in] usPort port number which isn't in use any longer
   * @return false if usPort is out of the range
   */
  bool ReleasePort(bool bRtp, unsigned short usPort);
};

#endif

